package initialize

import (
	"common/global"
	"context"
	"encoding/json"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"time"
)

/*接收设备发送的信息并存储至mongo数据库中*/
// 心率数据结构
type HeartRateData struct {
	EquipmentId string    `json:"equipment_id" bson:"equipment_id"` //设备ID
	HeartRate   int       `json:"heart_rate" bson:"heart_rate"`     //心率
	Timestamp   time.Time `json:"timestamp" bson:"timestamp"`       //时间
}

// 血压数据结构
type BloodPressureData struct {
	EquipmentId string    `json:"equipment_id" bson:"equipment_id"` //设备ID
	Systolic    int       `json:"systolic" bson:"systolic"`         //高压
	Diastolic   int       `json:"diastolic" bson:"diastolic"`       //低压
	Timestamp   time.Time `json:"timestamp" bson:"timestamp"`       //时间
}

func DeviceSubscription() {
	//获取mqtt的client
	client := InitMQTT()
	// 订阅心率数据
	client.Subscribe("health/heart_rate", 1, func(client mqtt.Client, msg mqtt.Message) {
		var hr HeartRateData
		if err := json.Unmarshal(msg.Payload(), &hr); err != nil {
			log.Printf("Error unmarshaling heart rate data: %v\n", err)
			return
		}
		// 设置时间戳
		now := time.Now()
		hr.Timestamp = now.Add(8 * time.Hour) //时区问题  增加八小时
		// 存储到MongoDB heart_rate集合
		collection := global.MonGoDatabase.Collection("heart_rate")
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_, err := collection.InsertOne(ctx, hr)
		if err != nil {
			log.Printf("Error inserting heart rate data: %v\n", err)
			return
		}
		log.Printf("Heart rate data stored for Equipment: %s\n", hr.EquipmentId)
	})

	// 订阅血压数据
	client.Subscribe("health/blood_pressure", 1, func(client mqtt.Client, msg mqtt.Message) {
		var bp BloodPressureData
		if err := json.Unmarshal(msg.Payload(), &bp); err != nil {
			log.Printf("Error unmarshaling blood pressure data: %v\n", err)
			return
		}
		// 设置时间戳
		now := time.Now()
		bp.Timestamp = now.Add(8 * time.Hour) //时区问题  增加八小时
		// 存储到MongoDB blood_pressure集合
		collection := global.MonGoDatabase.Collection("blood_pressure")
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_, err := collection.InsertOne(ctx, bp)
		if err != nil {
			log.Printf("Error inserting blood pressure data: %v\n", err)
			return
		}
		log.Printf("Blood pressure data stored for Equipment: %s\n", bp.EquipmentId)
	})
}
